import 'package:flutter/material.dart';

class ChatRefreshPage extends StatefulWidget {
  @override
  _ChatRefreshPageState createState() => _ChatRefreshPageState();
}

class _ChatRefreshPageState extends State<ChatRefreshPage> {
  List<String> _messages = List();
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    _messages = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "3",
      "4",
      "5",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "3",
      "4",
      "5",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "3",
      "4",
      "5",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "a",
      "aa",
      "aa",
      "a",
    ];

    _scrollController.addListener(() {
      print("_scrollController.offset == ${_scrollController.offset}");
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("chat refresh"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: RefreshIndicator(
              onRefresh: _onRefresh,
              child: ListView.builder(
                controller: _scrollController,
                itemBuilder: (context, index) {
                  return Text(_messages[index]);
                },
                itemCount: _messages.length,
              ),
            ),
          )
        ],
      ),
    );
  }

  Future<void> _onRefresh() async {
    Future.delayed(Duration(milliseconds: 500)).then((value) {
      List<String> messages = [
        "new",
        "new",
        "new",
        "new",
        "new",
        "new",
      ];
      _messages.insertAll(0, messages);
      setState(() {});
    });
  }
}
